<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>项目进度监控</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .project-card {
            margin-bottom: 15px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            border-radius: 8px;
            overflow: hidden;
        }
        .project-header {
            cursor: pointer;
            padding: 15px 20px;
            background-color: #f8f9fa;
            transition: all 0.3s ease;
        }
        .project-header:hover {
            background-color: #e9ecef;
        }
        .project-details {
            padding: 0; /* 修改为0，内部元素自行控制间距 */
            background-color: white;
            border-top: 1px solid #eee;
            position: relative; /* 为固定项目信息提供定位上下文 */
        }
        .progress {
            height: 24px;
            border-radius: 12px;
            flex-grow: 1;
        }
        .progress-bar {
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .progress-text {
            font-size: 14px;
            font-weight: bold;
            color: black;
            margin-right: 10px;
            min-width: 40px; /* 确保数字对齐 */
            text-shadow: 1px 1px 1px rgba(0,0,0,0.3);
        }
        .metric-card {
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            background-color: #f8f9fa;
        }
        .metric-value {
            font-size: 24px;
            font-weight: bold;
        }
        .metric-label {
            font-size: 14px;
            color: #6c757d;
        }
        .badge-custom {
            background-color: #6c757d;
            color: white;
            font-weight: normal;
        }
        .rotate-icon {
            transition: transform 0.3s ease;
        }
        .collapsed .rotate-icon {
            transform: rotate(-90deg);
        }
        .subproject-item {
            padding: 12px 15px;
            border-bottom: 1px solid #eee;
            transition: background-color 0.2s;
        }
        .subproject-item:hover {
            background-color: #f8f9fa;
        }
        .member-badge {
            font-size: 12px;
            margin-right: 5px;
            background-color: #e9ecef;
            color: #495057;
        }
        .loading-spinner {
            display: none;
            text-align: center;
            padding: 20px;
        }

        /* 新增样式 */
        .project-info-header {
            padding: 20px;
            background: white;
            position: sticky;
            top: 0;
            z-index: 10;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        }
        .subprojects-container {
            max-height: 700px;
            overflow-y: auto;
            padding: 0 20px;
        }
        .subprojects-list {
            padding-bottom: 20px; /* 为滚动条留出空间 */
        }
        .progress-container {
        display: flex;
        align-items: center;
        width: 200px;
    }

    </style>
</head>
<body>
    <div class="container py-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-tasks me-2"></i>项目进度监控</h2>
            <div>
                <span class="badge bg-primary p-2">
                    <i class="fas fa-user me-1"></i> {{ request.user.username }}
                </span>
            </div>
        </div>

        {% if not projects %}
        <div class="alert alert-info">
            <i class="fas fa-info-circle me-2"></i>您当前没有负责的项目
        </div>
        {% else %}
        <div class="row">
            <div class="col-md-12">
                {% for project in projects %}
                <div class="project-card">
                    <div class="project-header d-flex justify-content-between align-items-center collapsed"
                         data-bs-toggle="collapse"
                         data-bs-target="#project-{{ project.project_id }}"
                         aria-expanded="false">
                        <div class="d-flex align-items-center">
                            <i class="fas fa-project-diagram text-primary me-3" style="font-size: 1.5rem;"></i>
                            <div>
                                <h5 class="mb-0">{{ project.project_name }}</h5>
                                <small class="text-muted">创建时间: {{ project.created_at }}</small>
                            </div>
                        </div>
                        <div class="d-flex align-items-center">
                            <div class="progress-container me-4">
                                <span class="progress-text">{{ project.project_progress }}%</span>
                                <div class="progress">
                                    <div class="progress-bar {% if project.project_progress >= 80 %}bg-success{% elif project.project_progress >= 50 %}bg-info{% else %}bg-warning{% endif %}"
                                         role="progressbar"
                                         style="width: {{ project.project_progress }}%;"
                                         aria-valuenow="{{ project.project_progress }}"
                                         aria-valuemin="0"
                                         aria-valuemax="100">
                                    </div>
                                </div>
                            </div>
                            <span class="badge bg-secondary me-3">
                                <i class="fas fa-clock me-1"></i> {{ project.total_workload }}人天
                            </span>
                            <i class="fas fa-chevron-down rotate-icon"></i>
                        </div>

                    </div>

                    <div id="project-{{ project.project_id }}" class="collapse">
                        <div class="project-details">
                            <!-- 固定在顶部的项目信息 -->
                            <div class="project-info-header">
                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="metric-card">
                                            <div class="metric-value text-primary">
                                                {{ project.total_workload }} <small class="text-muted">人天</small>
                                            </div>
                                            <div class="metric-label">总工作量</div>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="metric-card">
                                            <div class="metric-value text-info">
                                                {{ project.project_progress }}%
                                            </div>
                                            <div class="metric-label">整体进度</div>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="metric-card">
                                            <div class="metric-value text-success">
                                                {{ project.created_at }}
                                            </div>
                                            <div class="metric-label">创建日期</div>
                                        </div>
                                    </div>
                                </div>

                                <h5 class="mt-3"><i class="fas fa-list-check me-2"></i>子任务列表</h5>
                            </div>

                            <!-- 子任务滚动区域 -->
                            <div class="subprojects-container">
                                <!-- 加载指示器 -->
                                <div id="loading-{{ project.project_id }}" class="loading-spinner">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="visually-hidden">加载中...</span>
                                    </div>
                                    <p class="mt-2">正在加载子任务数据...</p>
                                </div>

                                <!-- 子任务列表容器 -->
                                <div id="subprojects-{{ project.project_id }}" class="subprojects-list">
                                    <!-- 子任务将通过AJAX动态加载到这里 -->
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                {% endfor %}
            </div>
        </div>
        {% endif %}
    </div>

    <!-- 子任务项模板 (用于克隆) -->
    <template id="subproject-template">
        <div class="subproject-item">
            <div class="d-flex justify-content-between align-items-start mb-2">
                <div>
                    <i class="fas fa-circle-notch fa-xs text-primary me-2"></i>
                    <strong class="subproject-name"></strong>
                </div>
                <span class="badge bg-secondary subproject-progress"></span>
            </div>
            <div class="d-flex flex-wrap align-items-center">
                <small class="text-muted me-2">参与成员:</small>
                <div class="subproject-members"></div>
            </div>
        </div>
    </template>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 获取CSRF token
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
        const csrftoken = getCookie('csrftoken');

        // 监听所有折叠元素的显示事件
        // document.querySelectorAll('.collapse').forEach(element => {
        //     element.addEventListener('show.bs.collapse', function (e) {
        //         const projectId = this.id.replace('project-', '');
        //         loadSubprojects(projectId);
        //     });
        // });

        // 加载子任务数据
        function loadSubprojects(projectId) {
            const loadingElement = document.getElementById(`loading-${projectId}`);
            const subprojectsContainer = document.getElementById(`subprojects-${projectId}`);

            // 显示加载指示器
            loadingElement.style.display = 'block';
            subprojectsContainer.innerHTML = '';

            // 发送AJAX请求
            fetch('/monitor/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRFToken': csrftoken
                },
                body: `project_id=${projectId}`
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(data => {
                if (data.status === 'success') {
                    renderSubprojects(projectId, data.subprojects);
                } else {
                    throw new Error(data.message || '加载子任务失败');
                }
            })
            .catch(error => {
                console.error('加载子任务时出错:', error);
                subprojectsContainer.innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        加载子任务失败: ${error.message}
                    </div>
                `;
            })
            .finally(() => {
                loadingElement.style.display = 'none';
            });
        }

        // 渲染子任务列表
        function renderSubprojects(projectId, subprojects) {
            const container = document.getElementById(`subprojects-${projectId}`);
            const template = document.getElementById('subproject-template');

            if (subprojects.length === 0) {
                container.innerHTML = '<div class="alert alert-info">该项目暂无子任务</div>';
                return;
            }

            subprojects.forEach(subproject => {
                const clone = template.content.cloneNode(true);

                // 填充子任务数据
                clone.querySelector('.subproject-name').textContent = subproject.name;
                clone.querySelector('.subproject-progress').textContent = `${subproject.progress}%`;

                // 设置进度条颜色
                const progress = parseFloat(subproject.progress);
                const progressBadge = clone.querySelector('.subproject-progress');
                if (progress >= 80) {
                    progressBadge.classList.add('bg-success');
                } else if (progress >= 50) {
                    progressBadge.classList.add('bg-info');
                } else {
                    progressBadge.classList.add('bg-warning');
                }

                // 添加成员标签
                const membersContainer = clone.querySelector('.subproject-members');
                if (subproject.members && subproject.members.length > 0) {
                    subproject.members.forEach(member => {
                        const badge = document.createElement('span');
                        badge.className = 'badge member-badge';
                        badge.innerHTML = `<i class="fas fa-user me-1"></i>${member}`;
                        membersContainer.appendChild(badge);
                    });
                } else {
                    membersContainer.innerHTML = '<span class="text-muted">暂无成员</span>';
                }

                container.appendChild(clone);
            });
        }
        document.addEventListener('DOMContentLoaded', function() {
            // 自动展开特定项目
            const urlParams = new URLSearchParams(window.location.search);
            const projectId = urlParams.get('project');

            if (projectId) {
                setTimeout(() => {
                    const collapseElement = document.getElementById(`project-${projectId}`);
                    if (collapseElement) {
                        const bsCollapse = new bootstrap.Collapse(collapseElement, { toggle: true });
                        loadSubprojects(projectId);
                        collapseElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    }
                }, 100);
            }

            // 其他初始化代码
            document.querySelectorAll('.collapse').forEach(element => {
                element.addEventListener('show.bs.collapse', function(e) {
                    const projectId = this.id.replace('project-', '');
                    loadSubprojects(projectId);
                });
            });
        });
    </script>
</body>
</html>